/*
 * @Author: HuiWen Gong huiwings@163.com
 * @Date: 2022-11-07 15:48:51
 * @LastEditors: HuiWen Gong huiwings@163.com
 * @LastEditTime: 2023-12-14 14:12:31
 * @FilePath: \flutter_levin\lib\config\net\api.dart
 * @Description: 
 * 
 * Copyright (c) 2023 by ${git_name_email}, All Rights Reserved. 
 */
import 'package:dio/dio.dart';
import 'package:dio/io.dart';
import 'package:flutter_levin/provider/token_store.dart';

import 'kw_api.dart';

abstract class BaseHttp extends DioForNative {
  BaseHttp() {
    /// 初始化 加入app通用处理
    (transformer as BackgroundTransformer).jsonDecodeCallback = parseJson;
    interceptors.add(HeaderInterceptor());
    init();
  }

  void init();
}

class HeaderInterceptor extends InterceptorsWrapper {
  @override
  void onRequest(options, handler) {
    options.connectTimeout = const Duration(seconds: 15);
    options.receiveTimeout = const Duration(seconds: 15);

    var token = TokenStore.getToken();
    if (token.isNotEmpty) {
      options.headers['Authorization'] = token;
    }
    super.onRequest(options, handler);
  }
}

abstract class BaseRespData {
  int? code = 0;
  String? message;
  dynamic data;

  bool get success;

  BaseRespData({this.code, this.message, this.data});

  @override
  String toString() {
    return 'BaseRespData{code:$code,message:$message,data:$data}';
  }
}

///接口的code没有返回true的异常
class NotSuccessException implements Exception {
  int? code;
  String? message;

  NotSuccessException.fromRespData(BaseRespData respData) {
    code = respData.code;
    message = respData.message;
  }
}

///用于未登录或权限不够，需要授权操作
class UnAuthorizedException implements Exception {
  const UnAuthorizedException();
}
